package main

import (
	"errors"
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"log"
	"os"
	"sshstep-run/Component"
	"sshstep-run/Config"
)

func main() {
	if len(os.Args) == 0 {
		panic(errors.New("not found args"))
	}

	filePath := os.Args[len(os.Args)-1]
	file, err := os.Open(filePath)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	content, err := ioutil.ReadAll(file)
	if err != nil {
		panic(err)
	}

	config := Config.StepConfig{}
	err = yaml.Unmarshal([]byte(content), &config)
	if err != nil {
		panic(err)
	}

	for i := 0; i < len(config.Step); i++ {
		step := config.Step[i]
		component := Component.CreateComponent(step.Name)
		if component == nil {
			panic(errors.New(fmt.Sprintf("无法根据 %s 创建组件", step.Name)))
		}

		if config.Parameter != nil {
			for k, v := range config.Parameter {
				component.SetParameter(k, v)
			}
		}

		if step.Parameter != nil {
			for k, v := range step.Parameter {
				component.SetParameter(k, v)
			}
		}

		log.Printf("%s 开始执行\r\n", step.Name)

		err := component.Run()
		if err != nil {
			panic(err)
		}
	}

	log.Println("执行完成")
}
